import { _decorator, Component } from 'cc'
const { ccclass, property } = _decorator
import { TileManager } from './TileManager'
import { createUINode, randomInRange } from '../Utils'
import DataManager from '../RunTime/DataManager'
import { ResourceManager } from '../ResoucesManager/ResourceManager'

@ccclass('TileMapManager')
export class TileMapManager extends Component {
  async init() {
    const { mapInfo } = DataManager.getInstance(DataManager)
    const directoryPath = 'texture/tile/tile'
    const instance = ResourceManager.getInstance(ResourceManager)
    const spriteFrames = await instance.loadDirectory(directoryPath)

    const dataInst = DataManager.getInstance(DataManager)
    dataInst.tileInfo = []

    for (let i = 0; i < mapInfo.length; i++) {
      const column = mapInfo[i]
      dataInst.tileInfo[i] = []

      for (let j = 0; j < column.length; j++) {
        const item = column[j]
        if (item.src === null || item.type === null) {
          continue
        }

        let num = item.src
        if (num === 1 || num === 5 || num === 9) {
          if (i % 2 === 0 && j % 2 === 0) {
            //只对偶数的tile进行随机
            num += randomInRange(0, 4)
          }
        }

        const imgSrcPath = `tile (${num})`

        const node = createUINode('TileMap-' + i + '-' + j)
        const spriteFrame = spriteFrames.find(v => v.name === imgSrcPath) || spriteFrames[0]
        const tileManager = node.addComponent(TileManager)
        const type = item.type

        tileManager.init(type, spriteFrame, i, j)

        dataInst.tileInfo[i][j] = tileManager
        node.setParent(this.node)
      }
    }
  }
}
